package wechat

import (
	"github.com/wizjin/weixin"
	"hotel_Manager_Api/util"
	"github.com/martini-contrib/encoder"
	"github.com/go-martini/martini"
	"hotel_Manager_Api/model/dbModel"
	//"hotel_Manager_Api/model/dbEngin"
	"strings"
	"strconv"
	"hotel_Manager_Api/model/dbEngin"
	"fmt"
	"time"
	"crypto/md5"
	"net/http"
	"encoding/hex"
	"hotel_Manager_Api/handler/scheduleManage"
)

var mux *weixin.Weixin

func GetWeixin()*weixin.Weixin  {
	if mux == nil{
		appId := util.Config().MustValue("wechat","appId");
		appSecret := util.Config().MustValue("wechat","appSecret")
		token := util.Config().MustValue("wechat","token")
		mux = weixin.New(token, appId, appSecret)
		mux.HandleFunc(weixin.MsgTypeEventSubscribe,SubscriptHandler)
		mux.HandleFunc(weixin.MsgTypeText, Echo)
		mux.HandleFunc(weixin.MsgTypeEventScan,QrcodeScanHandler)
	}
	return mux

}

func CreateQrCode(enc encoder.Encoder,params martini.Params)(int,[]byte,error)  {
	deskId,_ := params["deskId"];

	wx:=GetWeixin()
	qr, err := wx.CreateQRLimitSceneByString(deskId)
	if err == nil {
		return 200,encoder.Must(enc.Encode(qr)),nil
	} else {
		return 500,nil,err
	}
}

func SubscriptHandler(w weixin.ResponseWriter, r *weixin.Request)  {
	usrName := r.FromUserName
	userInfo,err := mux.GetUserInfo(usrName)

	if err==nil{
		db := dbEngin.GetEnging()
		count,err:= db.Where("wechatId=?",usrName).Count(dbModel.ClientInfo{})
		if err!=nil{
			fmt.Println(err)
		}
		if count==0{
			user := new(dbModel.ClientInfo)
			user.Id = util.SnowFlakeNodeEntity.GenerateNewId()
			user.WeChatId = usrName
			user.HeadImgUrl = userInfo.HeadImageUrl
			user.NickName = userInfo.Nickname
			_,err = db.Insert(user)
			fmt.Println(err)
		}
	}else {
		fmt.Println(err)
	}
	if r.EventKey!="" && strings.HasPrefix(r.EventKey,"qrscene_"){
		QrcodeScanHandler(w,r)
	}
	//w.ReplyNews(weixin.Article{Title:"欢迎光临"+userInfo.Nickname,Url:"https://wechat.uliian.com",PicUrl:userInfo.HeadImageUrl})
}

func QrcodeScanHandler(w weixin.ResponseWriter, r *weixin.Request)  {
	fmt.Println("to scan hander")
	eventKey := strings.Replace(r.EventKey,"qrscene_","",1)
	deskId,_ := strconv.ParseInt(eventKey,10,64)
	deskOrderId,err := getDeskOrderId(deskId)
	if(err!=nil){
		fmt.Println(err)
		w.ReplyText("系统发生错误")
		return
	}

	var desk dbModel.Desk
	db := dbEngin.GetEnging()
	db.ID(deskId).Get(&desk)
	time := time.Now().Format("20060102150405")
	frontBaseUrl:= util.Config().MustValue("baseInfo","frontBaseUrl","")

	user := new(dbModel.ClientInfo)
	_,err = db.Where("wechatId=?",r.FromUserName).Get(user)
	if err != nil{
		fmt.Println(err)
	}
	url:= frontBaseUrl + "?deskOrderId="+fmt.Sprint(deskOrderId)+"&userId="+fmt.Sprint( user.Id)+"&createTime="+time+"&checkSum="+calcluteChecksum(time)
	w.ReplyNews(weixin.Article{Title:"欢迎光临"+"您就坐于："+  fmt.Sprintf("%d", desk.Floor)   + "搂" + desk.Name +"桌",Url:url,PicUrl:"http://wechatstatic.uliian.com/001de001870d0b15ed8d1d.jpg"},weixin.Article{Title:url})
}

func getDeskOrderId(deskId int64) (int64,error) {
	db := dbEngin.GetEnging()
	deskOrder := new(scheduleManage.DeskOrder)
	session := db.NewSession()
	has,err := session.Where("deskId=? AND orderStatus=?",deskId,scheduleManage.Begin).Get(deskOrder)
	if !has{
		fmt.Println("has no order")
		fmt.Println(deskOrder)
		deskOrder.Id = util.SnowFlakeNodeEntity.GenerateNewId()
		deskOrder.CreateTime = time.Now()
		deskOrder.OrderStatus = scheduleManage.Begin
		deskOrder.DinnerTime = time.Now()
		deskOrder.DeskId = deskId
		_,err = session.Insert(deskOrder)
	}
	session.Commit()
	if err!=nil{
		return -1,err
	}
	return deskOrder.Id,nil
}

///检查微信用户是否能够点餐
func VerifyWechatUserCanOrder(req *http.Request,res http.ResponseWriter)  {
	authInfoStr := req.Header.Get("Authorization")
	if authInfoStr == ""{
		res.WriteHeader(401)
		return
	}
	authInfo := strings.Split(authInfoStr," ")

	createTime,err := time.ParseInLocation("20060102150405",authInfo[0],time.Local)

	if(err!=nil){
		res.WriteHeader(401)
		return
	}

	expireTime := createTime.Add(time.Duration(3600*1000*1000*1000))
	now := time.Now().Unix()
	expire:= expireTime.Unix()

	if now>expire {
		res.WriteHeader(401)
		return
	}

	if(calcluteChecksum(authInfo[0])!=authInfo[1]){
		res.WriteHeader(401)
		return
	}
}

func calcluteChecksum(timeStr string)string{
	hasher := md5.New()
	txt := timeStr + "1qaz@WSX"
	hasher.Write([]byte(txt))
	return hex.EncodeToString(hasher.Sum(nil))
}

func Test()string  {
	deskId := 926273449037438976
	var desk dbModel.Desk
	_,err := dbEngin.GetEnging().ID(deskId).Get(&desk)
	fmt.Println(desk)
	fmt.Println(err)
	return desk.Name
}

func Echo(w weixin.ResponseWriter, r *weixin.Request) {
	//_ := r.Content			// 获取用户发送的消息
	w.ReplyOK()
}